/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveDeleteFormsRecords : CommandUtils.GrooveUtilBase
	{
		private string m_SpaceURI;
		private string m_FormsToolURI;
		private string m_FormURI;
		private string m_ViewURI;
		private string m_WhereClause;

		private bool m_CountOnly;
		private bool m_UnreadOnly;

		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveDeleteFormsRecords(i_Arguments));
		}
	
		public GrooveDeleteFormsRecords(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveDeleteFormsRecords [PARAMS...]";
			base.HelpMessage = 
				"GrooveDeleteFormsRecords\r\n\t" + 
				"Deletes records from the specified Groove forms tool.\r\n" +
				"Parameters:\r\n\t" +
				"/FormsTool=          The Web Services URI for the Groove forms tool\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/Form=              The Web Services URI for a specific Groove form]\r\n\t" +
				"[/View=              The Web Services URI for a specific Groove view]\r\n\t" +
				"[/WhereClause=       Query parameters (see Groove doc for syntax)]\r\n\t" +
				"[/CountOnly          Returns a count of deleted records (i.e. no actual data)]\r\n\t" +
				"[/UnreadOnly         Indicates to delete unread records only]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;
		
			m_FormsToolURI = base.GetParameterValue("FormsTool");
			if (System.String.IsNullOrEmpty(m_FormsToolURI))
			{
				base.DisplayUsage("You must specify a forms tool.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			//  The format for a Tool URI is:
			//    "/GWS/Groove/2.0/Tools/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2/ToolContainer/vk2xck8tanv5i"
			//
			//  The format for a Space URI is:
			//    "/GWS/Groove/2.0/Spaces/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2"

			string[] FormsToolURIParts = m_FormsToolURI.Split(new char[]{'/'});
			m_SpaceURI = "/GWS/Groove/2.0/Spaces/grooveTelespace/" + FormsToolURIParts[6];

			m_FormURI = base.GetParameterValue("Form");

			m_ViewURI = base.GetParameterValue("View");

			m_WhereClause = base.GetParameterValue("WhereClause");
			if (System.String.IsNullOrEmpty(m_WhereClause))
				m_WhereClause = "";

			m_CountOnly = base.GetParameterValueFlag("CountOnly");

			m_UnreadOnly = base.GetParameterValueFlag("UnreadOnly");
			
			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			GrooveWebServicesV12Helpers.Space Space = null;

			try
			{
				Space = base.Identity.OpenSpace(m_SpaceURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open space: " + Exception.Message);
				throw Exception;
			}

			GrooveWebServicesV12Helpers.Forms.FormsTool FormsTool = null;
			
			try
			{
				FormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)Space.OpenTool(m_FormsToolURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open forms tool: " + Exception.Message);
				throw Exception;
			}

			GrooveWebServicesV12Helpers.Forms.RecordDataSet RecordDataSet = null;
			System.Data.DataSet DataSet = null;

			// Query the forms tool to find the list of records to be deleted
			try
			{
				if (!System.String.IsNullOrEmpty(m_ViewURI))
				{
					RecordDataSet = FormsTool.QueryViewRecords
						(
						m_ViewURI,
						m_WhereClause,
						false,
						m_UnreadOnly
						);
				}
				else if (!System.String.IsNullOrEmpty(m_FormURI))
				{
					RecordDataSet = FormsTool.QueryFormRecords
						(
						m_FormURI,
						m_WhereClause,
						false,
						m_UnreadOnly
						);
				}
				else
				{
					RecordDataSet = FormsTool.QueryRecords
						(
						m_WhereClause,
						false,
						m_UnreadOnly
						);
				}

				DataSet = RecordDataSet.ToDataSet();
				System.Data.DataTable DataTable = DataSet.Tables["FormsRecordData"];

				int n=0;
				System.Collections.ArrayList uris = null;
				string[] RecordURIs;
				foreach (System.Data.DataRow DataRow in DataTable.Rows)
				{
					string uri = (string)DataRow["RecordURI"];
					if( uris==null )
					{
						uris = new System.Collections.ArrayList();
					}
					n++;
					uris.Add( uri );
					if( n>50 )
					{
						// Batch up to 50 deletions at a time, to avoid overloading dynamics
						RecordURIs = (string[]) uris.ToArray( typeof(string) );
						if( RecordURIs.Length > 0 )
						{
							// Delete the records in this batch
							FormsTool.RemoveRecords( RecordURIs );
						}
						n=0;
						uris = null;
					}
				}
				if( uris != null )
				{
					RecordURIs = (string[]) uris.ToArray( typeof(string) );
					if( RecordURIs.Length > 0 )
					{
						// Delete the remaining records
						FormsTool.RemoveRecords( RecordURIs );
					}
				}
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to delete records: " + Exception.Message);
				throw Exception;
			}


			if (m_CountOnly)
			{
				base.StandardOutput.WriteLine("<Data Count='" + RecordDataSet.Data.Length + "'/>");
			}
			else
			{
				//  Write dataset of deleted records to standard output
				DataSet.WriteXml(base.StandardOutput);
			}

			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}

	}
}